package com.youan.pangu.plus.validate;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youan.pangu.base.bean.ApplicationContextHelper;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

public class NotRepeatConstraintValidator implements ConstraintValidator<NotRepeat, Object> {
    private BaseMapper mapper ;
    private Class entityClass;
    private String columnName;
    @Override
    public void initialize(NotRepeat notRepeat) {
        mapper = ApplicationContextHelper.getBean(notRepeat.mapperClass());
        entityClass = notRepeat.entityClass();
        columnName = notRepeat.columnName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(columnName,value);
        List list =mapper.selectList(queryWrapper);
        return CollectionUtils.isEmpty(list);
    }
}
